package com.hhd.pdf;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.TextMarginFinder;
import com.hhd.pdf.components.ComponentsDelegate;
import com.hhd.pdf.context.GeneratorContext;
import com.hhd.pdf.exceptions.PdfException;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.IOException;

@Component
public class DefaultPdfGenerator extends AbstractPdfGenerator {
    @Autowired
    ComponentsDelegate componentsDelegate;

    @Override
    public void generated(GeneratorParameters generatorParameters) {
        int pageHeight = readPageHeight(generatorParameters);
        try {
            generatorParameters.setPageHeight(pageHeight);
            generateWidthPageHeight(generatorParameters);
        } catch (Exception e) {
            throw new PdfException(e.getMessage(), e);
        }
    }

    private int readPageHeight(GeneratorParameters generatorParameters) {
        PdfReader pdfReader = null;
        int numberOfPages = 1;
        try (FileInputStream inputStream = new FileInputStream(generatorParameters.getOutputPath())) {
            pdfReader = new PdfReader(inputStream);
            numberOfPages = pdfReader.getNumberOfPages();
            PdfReaderContentParser parser = new PdfReaderContentParser(pdfReader);
            TextMarginFinder textMarginFinder = parser.processContent(1, new TextMarginFinder());
            return (int) textMarginFinder.getHeight() + 120;
        } catch (IOException ignored) {
            try {
                pdfReader.close();
            } catch (Exception e) {
            }
        }

        int initPageHeight = generatorParameters.getInitPageHeight();
        return numberOfPages * initPageHeight + getPaddingTop(generatorParameters) + getPaddingBottom(generatorParameters);
    }

    private int getPaddingBottom(GeneratorParameters generatorParameters) {
        return generatorParameters.getPagePaddingTop();
    }

    private int getPaddingTop(GeneratorParameters generatorParameters) {
        return generatorParameters.getPagePaddingBottom();
    }

    @Override
    protected void parseComponent(Element element, GeneratorContext context) {
        componentsDelegate.parseComponent(element, context);
    }
}
